export const getterCookie = () => {
    return new Promise<chrome.cookies.Cookie[]>((resolve)=>{
        chrome.tabs.query({ active: true, currentWindow: true },(tab)=>{
            const url=tab[0].url as string
            const domain=new URL(url)
            const hostname=domain.hostname.split(".")
            // const levelDomain=`.${hostname[hostname.length-2]}.${hostname[hostname.length-1]}`
            const levelDomain=`.${hostname.slice(-2).join('.')}`
            chrome.cookies.getAll({domain:levelDomain},(ck)=>{
                resolve(ck)
            })
        })
    })
}
export const settingCookie = (ck:chrome.cookies.Cookie[],urlStr?:string) => {
    return new Promise((resolve)=>{
        chrome.tabs.query({ active: true, currentWindow: true },(tab)=>{
            const url= urlStr || tab[0].url as string
            const domain=new URL(url)
            Array.from(ck).forEach((item:chrome.cookies.Cookie)=>{
                const {hostOnly,session,...newItem}=item
                if (newItem.name.startsWith("__Host-")) return
                console.log("setting cookie is：",{url:domain.origin,...newItem});
                try{
                    chrome.cookies.set({url:domain.origin,...newItem},(res)=>{console.log("success setting：",res);})
                }
                catch(e){
                    console.log("error cookie：",newItem);
                }
            })
            resolve(true)
        })
    })
}
export const createNotification=(message:string,title="Cookie编辑器")=>{
    return new Promise<void>((resolve)=>{
        chrome.notifications.create({
            type:"basic",
            iconUrl:"../../icons/logo.png",
            title:title,
            message:message
        },(notificationId) => {
            setTimeout(async () => {
                await chrome.notifications.clear(notificationId)
                resolve()
            },3000)
        })
    })
}
export const getCurrentTabDomain=()=>{
    return new Promise<string>((resolve)=>{
        chrome.tabs.query({ active: true, currentWindow: true },(tab)=>{
            const url=tab[0].url as string
            const domain=new URL(url)
            const hostname=domain.hostname.split(".")
            const levelDomain=`.${hostname.slice(-2).join('.')}`
            resolve(levelDomain)
        })
    })
}